
package com.elong.common.http;

import java.util.LinkedList;
import java.util.Queue;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;
import java.util.concurrent.Future;

import org.apache.http.client.fluent.Async;
import org.apache.http.client.fluent.Content;
import org.apache.http.client.fluent.Request;
import org.apache.http.concurrent.FutureCallback;




public class FluentAsync {

    public static void main(String[] args) {
        ExecutorService threadpool = Executors.newFixedThreadPool(2);
        Async async = Async.newInstance().use(threadpool);
        
        Request[] requests = new Request[]{
          Request.Get("http://www.google.com.hk"),
          Request.Get("http://www.baidu.com"),
          Request.Get("http://www.apple.com"),
          Request.Get("http://www.elong.com")
        };
        
        Queue<Future<Content>> queue = new LinkedList<Future<Content>>();
        //异步执行GET请求
        for(final Request request : requests){
            Future<Content> future = async.execute(request,
                    new FutureCallback<Content>() {
                        
                        public void failed(Exception ex) {
                            System.out.println(ex.getMessage()
                                    + ": " + request);
                        }
                        
                        public void completed(Content arg0) {
                            System.out.println("request completed: " + request);
                        }
                        
                        public void cancelled() {
                            
                        }
            });
            queue.add(future);
        }
        
        while(!queue.isEmpty()){
            Future<Content> future = queue.remove();
            try {
                Content content = future.get();
                System.out.println(content.asString());
            } catch (Exception e) {
            }
        }
        System.out.println("done!");
        threadpool.shutdown();
    }
}
